package com.tan.kotlintest.base

import android.app.Dialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.annotation.LayoutRes
import android.support.v4.app.FragmentActivity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import com.gyf.barlibrary.ImmersionBar
import com.tan.kotlintest.R
import com.tan.kotlintest.helper.SharedPreferenceHelper
import com.tan.kotlintest.util.DialogUtil
import kotlinx.android.synthetic.main.base_activity_base.*
import kotlinx.android.synthetic.main.base_app_head.*

/*
 * Copyright (C) 2018 重庆一聊高科技有限公司
 * 版权所有
 *
 * 功能描述： Activity基类
 * 作者：txj
 * 创建时间：2018/9/7
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
abstract class BaseActivity : FragmentActivity() {

    private lateinit var mContext: Context
    private lateinit var mImmersionBar: ImmersionBar
    private lateinit var mDialogLoading: Dialog
    //private lateinit var decorator: FrameDecorator

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this

        val supportFullScreen = supportFullScreen()
        if (supportFullScreen) {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN)
        }
        setContentView(R.layout.base_activity_base)
        //1.设置状态栏样式
        if (!supportFullScreen) {
            setStatusBarStyle()
        }

        //2.设置是否屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        //3.初始化http请求request集合，保证在activity结束的时候终止http请求
        //4.初始化view
        initView()
        //5.添加view到content容器中，子类实现
        addIntoContent(getContentView())
        //8.view已添加到container
        onContentAdded()
    }

    /**
     * View初始化
     */
    private fun initView() {
        mDialogLoading = DialogUtil.showLoadingDialog(this)
        //默认处理title左上view的点击事件（back）
        left_fl.setOnClickListener {
            finish()
        }
        /*decorator = FrameDecorator.create(this)
        if (!canDrawOverlays()) {
            ToastUtil.showToast(applicationContext, R.string.no_permission)
        } else {
            decorator.show()
        }*/
    }

    /**
     * 添加view到容器中
     */
    private fun addIntoContent(view: View?) {
        if (view != null) {
            if (!attachMergeLayout()) {
                base_content.removeAllViews()
                base_content.addView(view)
            }
        } else {
            try {
                throw Exception("content view can not be null")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 是否需要显示顶部栏
     */
    protected fun needHeader(need: Boolean) {
        if (need) {
            head.visibility = View.VISIBLE
        } else {
            head.visibility = View.GONE
        }
    }

    /**
     * 设置title的文字
     */
    protected fun setTitleText(resource: Int) {
        if (resource > 0) {
            middle_title.setText(resource)
            middle_title.visibility = View.VISIBLE
        } else {
            middle_title.visibility = View.GONE
        }
    }

    protected fun setTitleText(str: String) {
        middle_title.text = str
        middle_title.visibility = View.VISIBLE
    }

    /**
     * 加载布局
     */
    protected abstract fun getContentView(): View?

    /**
     * 添加view完成回调，用于初始化数据
     */
    protected abstract fun onContentAdded()

    /**
     * @return return true 添加的layout以merge标签作为根布局, false layout不以merge标签作为根布局
     */
    private fun attachMergeLayout(): Boolean {
        return false
    }

    /**
     * 是否支持全屏
     */
    open fun supportFullScreen(): Boolean {
        return false
    }

    /**
     * 设置状态栏背景
     */
    private fun setStatusBarStyle() {
        if (!isImmersionBarEnabled()) {
            return
        }
        mImmersionBar = ImmersionBar.with(this)
        mImmersionBar.statusBarView(R.id.status_bar_view).barColorInt(getStatusBarColor())
                .statusBarDarkFont(true).init()
    }

    /**
     * 是否可以使用沉浸式
     */
    private fun isImmersionBarEnabled(): Boolean {
        return true
    }

    /**
     * 设置状态栏背景色
     */
    private fun getStatusBarColor(): Int {
        return if (Build.VERSION.SDK_INT > 22) {
            getColor(getStatusBarColorResId())
        } else {
            resources.getColor(getStatusBarColorResId())
        }
    }

    /**
     * 设置状态栏背景色资源id
     */
    private fun getStatusBarColorResId(): Int {
        return R.color.white
    }

    /**
     * 加载布局
     */
    protected fun inflate(@LayoutRes resource: Int): View {
        return LayoutInflater.from(this).inflate(resource, null)
    }

    /**
     * 获取UserId
     */
    public fun getUserId(): String {
        var userId = ""
        return if (AppManager.instance != null) {
            val chatUserInfo = AppManager.instance!!.getUserInfo()
            chatUserInfo.t_id.toString()
        } else {
            SharedPreferenceHelper.getAccountInfo(applicationContext).t_id.toString()
        }
    }

    private fun canDrawOverlays(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(this)
        } else {
            true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (canDrawOverlays()) {
            //decorator.dismiss()
        }
    }

}